package cn.iocoder.yudao.module.reading.controller.admin.audio;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.module.reading.controller.admin.audio.vo.*;
import cn.iocoder.yudao.module.reading.dal.dataobject.audio.AudioResourceDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.bookset.BookSetDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.PictureBookDO;
import cn.iocoder.yudao.module.reading.service.audio.AudioResourceService;
import cn.iocoder.yudao.module.reading.service.bookset.BookSetService;
import cn.iocoder.yudao.module.reading.service.book.PictureBookService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;

import java.util.List;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - 音频资源管理
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 音频资源管理")
@RestController
@RequestMapping("/reading/admin/audio")
@Validated
@Slf4j
public class AdminAudioResourceController {

    @Resource
    private AudioResourceService audioResourceService;
    @Resource
    private BookSetService bookSetService;
    @Resource
    private PictureBookService pictureBookService;
    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    /**
     * 检查当前用户是否为管理员
     * 音频资源管理只允许管理员操作
     */
    private void checkAdminPermission() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(401, "用户未登录");
        }
        if (!UserTypeEnum.ADMIN.getValue().equals(loginUser.getUserType())) {
            throw new ServiceException(403, "只有管理员才能管理音频资源");
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建音频资源")
    @PreAuthenticated
    public CommonResult<Long> createAudioResource(@Valid @RequestBody AudioResourceCreateReqVO createReqVO) {
        checkAdminPermission();
        return success(audioResourceService.createAudioResource(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新音频资源")
    @PreAuthenticated
    public CommonResult<Boolean> updateAudioResource(@Valid @RequestBody AudioResourceUpdateReqVO updateReqVO) {
        checkAdminPermission();
        audioResourceService.updateAudioResource(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除音频资源")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthenticated
    public CommonResult<Boolean> deleteAudioResource(@RequestParam("id") Long id) {
        checkAdminPermission();
        audioResourceService.deleteAudioResource(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得音频资源")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<AudioResourceAdminRespVO> getAudioResource(@RequestParam("id") Long id) {
        checkAdminPermission();
        AudioResourceDO audioResource = audioResourceService.getAudioResource(id);
        AudioResourceAdminRespVO respVO = BeanUtils.toBean(audioResource, AudioResourceAdminRespVO.class);

        // 填充绘本集和绘本标题信息
        fillBookInfo(respVO);

        // 将相对路径转换为完整URL
        respVO.setAudioUrl(staticResourceUrlUtils.toFullUrl(respVO.getAudioUrl()));
        respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));

        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得音频资源分页")
    @PreAuthenticated
    public CommonResult<PageResult<AudioResourceAdminRespVO>> getAudioResourcePage(@Valid AudioResourcePageReqVO pageReqVO) {
        checkAdminPermission();
        PageResult<AudioResourceDO> pageResult = audioResourceService.getAudioResourcePage(pageReqVO);

        // 转换为响应VO并处理URL
        PageResult<AudioResourceAdminRespVO> respPageResult = BeanUtils.toBean(pageResult, AudioResourceAdminRespVO.class);
        respPageResult.getList().forEach(respVO -> {
            // 填充绘本集和绘本标题信息
            fillBookInfo(respVO);
            // 转换URL
            convertUrlsToFull(respVO);
        });

        return success(respPageResult);
    }

    @GetMapping("/list")
    @Operation(summary = "获得音频资源列表")
    @PreAuthenticated
    public CommonResult<List<AudioResourceAdminRespVO>> getAudioResourceList(@Valid AudioResourceListReqVO listReqVO) {
        checkAdminPermission();
        List<AudioResourceDO> list = audioResourceService.getAudioResourceList(listReqVO);

        // 转换为响应VO并处理URL
        List<AudioResourceAdminRespVO> respList = BeanUtils.toBean(list, AudioResourceAdminRespVO.class);
        respList.forEach(respVO -> {
            // 填充绘本集和绘本标题信息
            fillBookInfo(respVO);
            // 转换URL
            convertUrlsToFull(respVO);
        });

        return success(respList);
    }

    @PostMapping("/batch-update-status")
    @Operation(summary = "批量更新音频资源状态")
    @PreAuthenticated
    public CommonResult<Boolean> batchUpdateAudioResourceStatus(
            @RequestBody @Valid AudioResourceBatchUpdateStatusReqVO batchUpdateReqVO) {
        checkAdminPermission();
        audioResourceService.batchUpdateAudioResourceStatus(batchUpdateReqVO.getIds(), batchUpdateReqVO.getEnabled());
        return success(true);
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除音频资源")
    @PreAuthenticated
    public CommonResult<Boolean> batchDeleteAudioResource(@RequestBody @Valid AudioResourceBatchDeleteReqVO batchDeleteReqVO) {
        checkAdminPermission();
        audioResourceService.batchDeleteAudioResource(batchDeleteReqVO.getIds());
        return success(true);
    }

    @PostMapping("/update-sort-order")
    @Operation(summary = "更新音频资源排序")
    @PreAuthenticated
    public CommonResult<Boolean> updateAudioResourceSortOrder(
            @RequestBody @Valid AudioResourceUpdateSortOrderReqVO updateSortOrderReqVO) {
        checkAdminPermission();
        audioResourceService.updateAudioResourceSortOrder(updateSortOrderReqVO.getId(), updateSortOrderReqVO.getSortOrder());
        return success(true);
    }

    @GetMapping("/categories")
    @Operation(summary = "获取音频分类列表")
    @PreAuthenticated
    public CommonResult<List<String>> getAudioCategories() {
        checkAdminPermission();
        return success(audioResourceService.getAudioCategories());
    }

    @GetMapping("/languages")
    @Operation(summary = "获取音频语言列表")
    @PreAuthenticated
    public CommonResult<List<String>> getAudioLanguages() {
        checkAdminPermission();
        return success(audioResourceService.getAudioLanguages());
    }

    /**
     * 填充绘本集和绘本标题信息
     */
    private void fillBookInfo(AudioResourceAdminRespVO respVO) {
        // 填充绘本集标题
        if (respVO.getBookSetId() != null) {
            BookSetDO bookSet = bookSetService.getBookSet(respVO.getBookSetId());
            if (bookSet != null) {
                respVO.setBookSetTitle(bookSet.getTitle());
            }
        }

        // 填充绘本标题
        if (respVO.getBookId() != null) {
            PictureBookDO book = pictureBookService.getPictureBook(respVO.getBookId());
            if (book != null) {
                respVO.setBookTitle(book.getTitle());
            }
        }
    }

    /**
     * 将相对路径转换为完整URL
     */
    private void convertUrlsToFull(AudioResourceAdminRespVO respVO) {
        respVO.setAudioUrl(staticResourceUrlUtils.toFullUrl(respVO.getAudioUrl()));
        respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));
    }
}
